var express = require('express');
var router = express.Router();
var session = require('express-session');
var crypto = require('crypto');
var path = require("path")
var child_process = require('child_process');
var fs = require('fs');
var os = require('os');
var async = require('async');

var db = require("./../../utils/db.js");
var jenkins = require('jenkins')({baseUrl: 'http://dpf:pengfei123@localhost:8080', crumbIssuer: true});
//jenkins 新建 job 必须传的项目配置文件 内容
var jobXmlTemplate = "<?xml version='1.0' encoding='UTF-8'?>\
    <project>\
    <keepDependencies>false</keepDependencies>\
    <properties/>\
    <scm class='hudson.scm.NullSCM'/>\
    <canRoam>false</canRoam>\
    <disabled>false</disabled>\
    <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>\
    <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>\
    <triggers/>\
    <concurrentBuild>false</concurrentBuild>\
    <builders/>\
    <publishers/>\
    <buildWrappers/>\
    </project>";

//svn 仓库 根路径
var svnRepositoriesRoot = 'F:/Repositories';

//项目成员 字符串分隔符
var PROJECT_MEMBER_SEPARATOR = ',';

// 获取项目列表
router.get('/listAll', function (req, res, next) {
    var sql = "select *, (select person_name from base_user u where u.id=p.project_leader_id) as project_leader_name from project_base p where 1=1";

    db.query(sql, function (err, rows) {
        if (!err && rows.length >= 0) {
            res.render('admin/project/listAll', {
                dataList: rows
            });
        } else {
            res.render('error', {
                message: err.message,
                error: err
            });
        }
    });

});
// 新增用户页面
router.get('/add', function (req, res, next) {
    var userSql = "select * from base_user";
    db.query(userSql, function (err, rows) {
        if (!err) {
            res.render('admin/project/edit', {
                project: {
                    id: '',
                    projectName: '',
                    projectCode: '',
                    projectSvnAddress: '',
                    projectMemberIdStr: '',
                    projectLeaderId: ''
                },
                userList: rows
            });
        }
    });

});

/**
 * 修改
 */
router.get("/edit/:id", function (req, res, next) {
    var id = req.params.id;
    var projectSql = "select * from project_base p where p.id =" + id;
    var userSql = "select * from base_user";

    async.series([
        function (callback) {
            db.query(projectSql, function (err, rows) {
                callback(err, rows);
            })
        },
        function (callback) {
            db.query(userSql, function (err, rows) {
                callback(err, rows);
            })
        }
    ], function (err, values) {
        if (!err && values && values[0][0] && values[1][0]) {
            res.render('admin/project/edit', {
                project: {
                    id: values[0][0].id,
                    projectName: values[0][0].project_name,
                    projectCode: values[0][0].project_code,
                    projectSvnAddress: values[0][0].project_svn_adress,
                    projectMemberIdStr: values[0][0].project_member_id_str,
                    projectLeaderId: values[0][0].project_leader_id
                },
                userList: values[1]
            });
        } else {
            res.send("系统内部错误");
        }
    });

});


/**
 * 增加
 */
router.post('/save', function (req, res, next) {
    var projectName = req.body.projectName ? req.body.projectName.trim() : '';
    var projectCode = req.body.projectCode ? req.body.projectCode.trim() : '';
    var projectSvnAddress = req.body.projectSvnAddress ? req.body.projectSvnAddress.trim() : '';
    var projectLeaderId = req.body.projectLeaderId ? parseInt(req.body.projectLeaderId.trim()) : 1;
    // var projectMemberIdStr = req.body.projectMember && req.body.projectMember instanceof Array ?  : '';
    var projectMemberIdStr = '';
    if (req.body.projectMember) {
        if (req.body.projectMember instanceof Array) {
            projectMemberIdStr = req.body.projectMember.join(PROJECT_MEMBER_SEPARATOR);
        } else {
            projectMemberIdStr = req.body.projectMember;
        }
    } else {
        projectMemberIdStr = '';
    }
    var id = req.body.id;
    var sql = '';
    if (id) {
        sql = "update project_base set project_name = '" + projectName + "',project_code = '" + projectCode + "',project_svn_adress = '" + projectSvnAddress + "',project_member_id_str = '" + projectMemberIdStr + "', project_leader_id=" + projectLeaderId + " where id =  '" + id + "'";
    } else {
        sql = "insert into project_base(project_name,project_code,project_svn_adress,project_member_id_str,project_member_name_str,project_leader_id) values('" + projectName + "','" + projectCode + "','" + projectSvnAddress + "','" + projectMemberIdStr + "', '', " + projectLeaderId + ")";
    }
    db.query(sql, function (err, rows) {
        if (!err) {
            child_process.exec('svnadmin create ' + svnRepositoriesRoot + '/' + projectCode, function (error, stdout) {
                if (error) {
                    console.log('SVN 仓库创建失败，请手动创建，创建命令：svnadmin create ' + svnRepositoriesRoot + '/' + projectCode)
                } else {
                    console.log(os.platform());

                    var osStr = os.platform();
                    if ('win32' === osStr) {   //window 系统，visual SVN Server
                        var svnAuthzPath = svnRepositoriesRoot + '/' + projectCode + '/conf/VisualSVN-SvnAuthz.ini';
                        var svnAuthzContent = '[/]' + os.EOL;
                        if (projectMember) {
                            var projectMemberArr = projectMember.split(PROJECT_MEMBER_SEPARATOR);
                            for (var i = 0; i < projectMemberArr.length; i++) {
                                svnAuthzContent += projectMemberArr[i] + '=rw' + os.EOL;
                            }

                        }
                        fs.writeFile(svnAuthzPath, svnAuthzContent, function (err) {
                            if (err) {
                                console.error(err);
                            }
                        });
                    } else {    //todo 其它系统不一定这样操作

                    }

                }

                //jenkins
                jenkins.job.create({
                    name: projectCode,
                    xml: jobXmlTemplate
                }, function (err) {
                    if (err) {
                        console.log(err);
                    }
                });

                res.redirect("/project/listAll");
            });

        } else {
            res.json({
                errcode: 1,
                message: '新增失败'
            });
        }
    });


});





/**
 * 删除
 */
router.get("/delete/:id", function (req, res) {
    var id = req.params.id;

    var sql = "select * from project_base where id =  '" + id + "'";
    db.query(sql, function (err, rows) {
        if (!err && rows.length > 0) {
            var projectCode = rows[0].project_code;
            if (projectCode) {
                var path = svnRepositoriesRoot + '/' + projectCode;
                deleteFolderRecursive(path);

                var sql = "delete from project_base where id = '" + id + "'";
                db.query(sql, function (err, rows) {
                    if (!err) {
                        jenkins.job.destroy(projectCode, function (err) {
                            if (err) {
                                console.log(err);
                            }
                        });
                        res.redirect("/project/listAll");
                    } else {
                        res.json({
                            errcode: 1,
                            message: '删除失败'
                        });
                    }
                });
            }
        } else {
            res.send("该项目不存在");
        }
    });
});

/**
 * 查询
 */
router.post("/search", function (req, res, next) {
    var projectName = req.body.projectName;
    var projectCode = req.body.projectCode;
    var sql = "select *, (select person_name from base_user u where u.id=p.project_leader_id) as project_leader_name from project_base p where 1=1 ";
    if (projectName) {
        sql += "and project_name like '%" + projectName + "%'";
    }
    if (projectCode) {
        sql += "and project_code like '%" + projectCode + "%'";
    }
    db.query(sql, function (err, rows) {
        if (err) {
            res.send("查询失败: " + err);
        } else {
            res.render("admin/project/listAll", {
                title: "项目列表",
                dataList: rows,
                projectName: projectName,
                projectCode: projectCode
            });
        }
    });
});

/**
 * 最近的项目列表（工作台）
 */
router.get("/recentProjectList", function (req, res, next) {
    var loginedUser = req.session.loginedUser;
    var sql = "select *, (select person_name from base_user u where u.id=p.project_leader_id) as project_leader_name from project_base p where p.project_member_id_str like '%" + loginedUser.id + "%' limit 0,8 ";
    db.query(sql, function (err, rows) {
        if (!err) {
            res.json({
                errcode: 0,
                message: '获取最近项目成功',
                data: rows
            });
        } else {
            res.send("查询失败: " + err);
        }
    });
});

//项目详情页
router.get("/detail/:id", function (req, res, next) {
    var id = req.params.id;
    if (!id) {
        res.render('error', {error: error});
    } else {
        req.session.projectId = id;
        var sql = "select *, (select person_name from base_user u where u.id=p.project_leader_id) as project_leader_name from project_base as p left join version_base as v on p.id=v.project_base_id where p.id = " + id + " ORDER BY v.version_release_time DESC limit 1";
        db.query(sql, function (err, rows) {
            if (rows && rows.length >= 0) {
                req.session.project = rows[0];
            }

            res.redirect('/process/historyVersion/listAll');
        });
    }


});

/**
 * 递归删除文件夹
 * @param path
 */
function deleteFolderRecursive(path) {
    if (fs.existsSync(path)) {
        fs.readdirSync(path).forEach(function (file) {
            var curPath = path + "/" + file;
            if (fs.statSync(curPath).isDirectory()) { // 递归
                deleteFolderRecursive(curPath);
            } else { // 删除文件
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
}


module.exports = router;
